/*
 * LiveRelayServer.h
 *
 *  Created on: 2016年4月30日
 *      Author: terry
 */

#ifndef LIVERELAYSERVER_H_
#define LIVERELAYSERVER_H_

#include "BasicType.h"
#include "TCriticalSection.h"
#include "TMap.h"
#include "RtspRelay.h"
#include "TThread.h"
#include "TEvent.h"
#include "SharedPtr.h"

#include <client.h>
#include <messagehandler.h>
#include <connectionlistener.h>

#include "MediaControlStanza.h"

using namespace gloox;


class LiveRelayServer : public comn::Thread, public ConnectionListener , public IqHandler
{
public:
	LiveRelayServer();
	virtual ~LiveRelayServer();

    virtual bool start();
    virtual void stop();

    void onRtspCasterEvent(const RtspCasterEvent* event);


protected:
	virtual int run();
	virtual void doStop();
	virtual bool startup();
	virtual void cleanup();

	virtual bool handleIq( const IQ& iq );
	virtual void handleIqID( const IQ& iq, int context );

	virtual	void onConnect();
	virtual	void onDisconnect( ConnectionError e );
	virtual	bool onTLSConnect( const CertInfo& info );

	void openClient();
	void closeClient();

	std::string getJid() const;

protected:
    void clientConnected(const std::string& jid);
    void clientDisconnected(const std::string& jid);

    void queryMediaFormat(const std::string& jid);
    void setupStream(const std::string& jid, const std::string& videoUrl, const std::string& audioUrl, const std::string& chl);
    void teardownStream(const std::string& jid, const std::string& chl);

    void onCommandDesc(const JID& jid, IQ::IqType subtype, const MediaControlStanza* stanza);
    void onCommandSetup(const JID& jid, IQ::IqType subtype, const MediaControlStanza* stanza);
    void onCommandTeardown(const JID& jid, IQ::IqType subtype, const MediaControlStanza* stanza);

    std::string replaceIP(const std::string& url);

    std::string getDomain();

    int getTransportProtocol();

    bool parseStreamName(const std::string& name, std::string& dev, std::string& chl);
    std::string makeStreamName(const std::string& dev, const std::string& chl);

protected:
    typedef comn::Map< std::string, std::string >   StringMap;
    StringMap	m_nameMap;

	std::shared_ptr< Client >	m_client;
	comn::Event	m_event;
    bool    m_setupReady;

};

#endif /* LIVERELAYSERVER_H_ */
